/*
 * ModelCC, distributed under ModelCC Shared Software License, www.modelcc.org
 */

package org.modelcc.language.syntax.builder;

import org.modelcc.language.factory.ListContent;
import org.modelcc.language.syntax.ParserMetadata;
import org.modelcc.language.syntax.Symbol;
import org.modelcc.language.syntax.SymbolBuilder;

/**
 * List symbol builder (L ::= E L) 
 * 
 * @author Fernando Berzal (berzal@acm.org)
 */
public class ListSymbolBuilder extends SymbolBuilder
{
	private int list;
	private int element;
	
	/**
	 * Constructor
	 * @param list List index within rule RHS (-1 if not present)
	 * @param element Element index within rule RHS (-1 if not present)
	 */
	public ListSymbolBuilder(int list, int element)
	{
		this.list = list;
		this.element = element;
	}

	@Override
	public boolean build(Symbol t, ParserMetadata data) 
	{
		Object[] l;
        ListContent restContents = null;
        
        if (list!=-1)
        	restContents = (ListContent) t.getContent(list).getUserData();
        if (restContents == null)
        	restContents = new ListContent(new Object[0]);
        
        Object[] rest = restContents.getContent();
        
        if (element!=-1) {
        	l = new Object[rest.length+1];
        	l[0] = t.getContent(element).getUserData();
        	for (int i=0; i<rest.length;i++)
        		l[i+1] = rest[i];
        } else {
        	l = rest;
        }

        t.setUserData(new ListContent(l,restContents.getSymbol(),restContents.getRuleSymbol()));
        return true;
	}	
}